<template>
  <md-main>
    <el-collapse-transition>
      <div class="md-body" v-show="showSearch">
        <el-form :model="search" ref="search" size="small" :inline="true">
          <el-form-item label="字典标签" prop="dictLabel">
            <el-input v-model="search.dictLabel" placeholder="请输入字典标签" clearable class="w150" />
          </el-form-item>
          <el-form-item label="字典值" prop="dictValue">
            <el-input v-model="search.dictValue" placeholder="请输入字典值" clearable class="w150" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <md-dict-select :options="statusList" :props="{label:'label',value:'value'}" v-model="search.status" placeholder="请选择状态" class="w150"></md-dict-select>
          </el-form-item>
          <el-form-item>
            <md-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery()">搜索</md-button>
            <md-button icon="el-icon-refresh" size="mini" @click="handleQueryReset()">重置</md-button>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>

    <div class="md-body md-table">
      <md-toolbar>
        <md-button type="primary" size="small" plain :prems="['system:dict:add']" @click="handleAdd()">新增</md-button>
        <md-button type="success" size="small" plain :prems="['system:dict:remove']" :disabled="tableSelectIds.length===0" @click="handleDelete()">批量删除</md-button>

        <template slot="right">
          <md-button size="mini" icon="el-icon-search" circle @click="showSearch=!showSearch"></md-button>
          <md-button type="primary" size="mini" icon="el-icon-refresh" circle @click="getTableDataList()"></md-button>
        </template>
      </md-toolbar>

      <el-table v-loading="tableLoading" :data="tableData" @selection-change="handleTableSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="字典标签" align="center" prop="dictLabel" width="100px" />
        <el-table-column label="字典值" prop="dictValue" align="center" width="100px" />
        <el-table-column label="排序" prop="dictSort" width="100px"></el-table-column>
        <el-table-column label="是否默认" align="center" prop="isDefault" min-width="100px">
          <template slot-scope="{ row }">
            <md-dict-tag :options="isDefaultList" :props="{label:'label',value:'value'}" :value="row.isDefault"></md-dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" min-width="100px">
          <template slot-scope="{ row }">
            <md-dict-tag :options="statusList" :props="{label:'label',value:'value'}" :value="row.status"></md-dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="150px" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" fixed="right" width="150px">
          <template slot-scope="scope">
            <md-button size="mini" type="text" icon="el-icon-edit" :prems="['system:dict:edit']" @click="handleUpdate(scope.row)">修改</md-button>
            <md-button size="mini" type="text" icon="el-icon-delete" :prems="['system:dict:remove']" @click="handleDelete(scope.row)">删除</md-button>
          </template>
        </el-table-column>
      </el-table>

      <md-pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="search.pageIndex" :limit.sync="search.pageSize" @pagination="getTableDataList" />
    </div>

    <!-- 添加或修改配置对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="request" :rules="rules" size="small" label-width="80px" label-position="right">
        <el-form-item label="数据标签" prop="dictLabel">
          <el-input v-model="request.dictLabel" placeholder="请输入数据标签" />
        </el-form-item>
        <el-form-item label="数据键值" prop="dictValue">
          <el-input v-model="request.dictValue" placeholder="请输入数据键值" />
        </el-form-item>
        <el-form-item label="样式属性" prop="cssClass">
          <el-input v-model="request.cssClass" placeholder="请输入样式属性" />
        </el-form-item>
        <el-form-item label="回显样式" prop="listClass">
          <el-select v-model="request.listClass" placeholder="请选择回显样式" style="width: 100%">
            <el-option v-for="item in listClassOptions" :key="item.value" :label="item.label + '(' + item.value + ')'" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="显示排序" prop="dictSort">
          <el-input-number v-model="request.dictSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="是否默认" prop="isDefault">
          <md-dict-radio-group :options="isDefaultList" :props="{label:'label',value:'value'}" v-model="request.isDefault"></md-dict-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <md-dict-radio-group :options="statusList" :props="{label:'label',value:'value'}" v-model="request.status"></md-dict-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="request.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleSubmit">确 定</el-button>
        <el-button size="small" @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
  </md-main>
</template>

<script>
import { insertDictData, updateDictData, listPageDictData, delDictData, getDictData } from '@/api/system/dict.data.service.js'
export default {
  name: 'MdSystemDictDataComponent',
  props: ['params'],
  data () {
    return {
      statusEnum, statusList, isDefaultEnum, isDefaultList,
      listClassOptions,
      // 显示隐藏查询条件
      showSearch: true,
      // 查询参数
      search: searchParams,
      // 创建时间
      dateRange: [],
      // 列表加载
      tableLoading: false,
      tableData: [],
      tableTotal: 0,
      // 已选择的列表数据
      tableSelectIds: [],
      // 添加/编辑请求参数
      request: requestParams,
      rules: rules,
      // 添加/编辑弹窗
      dialog: {
        title: '添加字典数据',
        open: false
      }
    }
  },
  watch: {
    params: {
      handler (val) {
        if (val) {
          this.search.dictType = val.dictType
          this.request.dictType = val.dictType
          this.getTableDataList()
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    this.getTableDataList()
  },
  methods: {
    /** 获取字典数据 */
    async getTableDataList () {
      this.tableLoading = true
      this.tableData = []

      try {
        const res = await listPageDictData(this.search)

        this.tableData = res.data.items
        this.tableTotal = res.data.totalItems
      } catch (error) {
        console.log(error)
      }

      this.tableLoading = false
    },
    /** 表格复选框事件 */
    handleTableSelectionChange (event) {
      this.tableSelectIds = event.map(m => { return m.dictCode })
    },
    /** 搜索 */
    handleQuery () {
      this.search.pageIndex = 1

      this.getTableDataList()
    },
    /** 重置搜索 */
    handleQueryReset () {
      this.search = { ...searchParams }

      this.getTableDataList()
    },
    // 重置表单数据
    handleReset () {
      this.request = { ...requestParams }
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    /** 删除字典 */
    async handleDelete (row) {
      try {
        const ids = row?.dictCode || this.tableSelectIds

        await this.$confirm(`是否确认删除编号为${ids}的数据项？`)

        await delDictData(ids)

        this.$message.success('删除成功')

        this.handleQuery()
      } catch (error) {
        console.log(error)
      }
    },
    /** 添加字典 */
    async handleAdd () {
      try {
        this.handleReset()

        this.dialog.title = '添加字典数据'

        this.dialog.open = true

        this.request = { ...requestParams }
      } catch (error) {
        console.log(error)
      }
    },
    /** 修改字典 */
    async handleUpdate (row) {
      try {
        this.handleReset()

        const res = await getDictData(row.dictCode)

        this.request = res.data

        this.dialog.open = true

        this.dialog.title = '修改字典数据'

      } catch (error) {
        console.log(error)
      }
    },
    /** 提交 */
    handleSubmit () {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return
        }

        try {
          const params = Object.assign({}, { ...this.request })

          await (params.dictCode === undefined ? insertDictData : updateDictData)(params)

          this.$message.success(params.dictCode === undefined ? '添加成功' : '修改成功')

          this.dialog.open = false

          this.handleQuery()
        } catch (error) {
          console.log(error)
        }
      })
    },
    /** 取消 */
    handleCancel () {
      this.dialog.open = false

      this.handleReset()
    }
  }
}
/** 数据标签回显样式 */
const listClassOptions = [
  {
    value: 'default',
    label: '默认'
  },
  {
    value: 'primary',
    label: '主要'
  },
  {
    value: 'success',
    label: '成功'
  },
  {
    value: 'info',
    label: '信息'
  },
  {
    value: 'warning',
    label: '警告'
  },
  {
    value: 'danger',
    label: '危险'
  }
]

const searchParams = {
  dictName: undefined,
  dictType: undefined,
  status: undefined,
  createBy: undefined,
  updateBy: undefined,
  beginDate: undefined,
  endDate: undefined,
  orderBy: 'dict_sort',
  isDesc: false,
  pageIndex: 1,
  pageSize: 10
}

const requestParams = {
  dictCode: undefined,
  dictLabel: undefined,
  dictValue: undefined,
  cssClass: undefined,
  dictType: undefined,
  listClass: 'default',
  dictSort: 0,
  isDefault: 'N',
  status: "0",
  remark: undefined
}

const rules = {
  dictLabel: [{ required: true, message: '请输入数据标签', trigger: 'blur' }],
  dictValue: [{ required: true, message: '请输入数据键值', trigger: 'blur' }],
  dictSort: [{ required: true, message: '请输入数据顺序', trigger: 'blur' }]
}

// 字典状态
const statusEnum = {
  '0': { label: '正常', type: 'success' },
  '1': { label: '停用', type: 'danger' }
}
const statusList = Object.keys(statusEnum).map(m => { return { value: m, label: statusEnum[m].label } })

// 是否默认
const isDefaultEnum = {
  'Y': { label: '是', type: 'success' },
  'N': { label: '否', type: 'danger' },
}
const isDefaultList = Object.keys(isDefaultEnum).map(m => { return { value: m, label: isDefaultEnum[m].label } })
</script>